package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Slf4j
public class OrderController {
    // 单机版
    // private static final String PAYMENT_URL = "localhost:8011";

    // eureka 服务发现后只需要指定服务名, 另外可以开启负载均衡
    private static final String PAYMENT_URL = "cloud-provider-payment";

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/")
    public String index() {
        return "consumer -> consul";
    }

    @GetMapping("/consumer/payment/create")
    public CommonResult create(Payment payment) {
        log.info("create: " + payment);
        return restTemplate.postForObject("http://" + PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult get(@PathVariable("id") Long id) {
        return restTemplate.getForObject("http://" + PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    @GetMapping("/rule/random/consumer/payment/get/{id}")
    public CommonResult get02(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity("http://" + PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        }
        return new CommonResult(444, "操作失败");
    }

}
